package com.gs.synedocket.fragment;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.gs.synedocket.R;
import com.gs.synedocket.adapter.DocketLogAdapter;
import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.apiresult.PagedList;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.dto.DocketDto;
import com.gs.synedocket.db.dto.DocketSummaryDto;
import com.gs.synedocket.db.dto.ShortDto;
import com.gs.synedocket.db.query.DocketQuery;
import com.gs.synedocket.dialog.DialogUtil;
import com.gs.synedocket.dialog.LoadingDialogUtils;
import com.gs.synedocket.dialog.ShortDialog;
import com.gs.synedocket.dialog.ToastDialogUtils;
import com.gs.synedocket.fragment.base.BaseListFragment;
import com.gs.synedocket.presenter.DocketLogPresenter;
import com.gs.synedocket.util.DateUtil;
import com.gs.synedocket.util.DocketUtil;
import com.gs.synedocket.util.SPUtil;
import com.gs.synedocket.view.IDocketLogView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DocketLogFragment extends BaseListFragment<IDocketLogView, DocketLogPresenter, DocketDto, DocketQuery> implements IDocketLogView {

    private DocketLogAdapter adapter;
    private TextView tvToday, tvMonth, tvTruck, tvTitle, tvRvTitle,
            tvSite, tvDate, tvTruckSel, tvPlant, tvSel, tvSearch, tvStatus;
    private ImageView ivBack;
    private LinearLayout llTruck, llSearch;
    private String selId, what;
    private boolean isEnd, isParam;
    private Calendar calendarStart, calendarEnd;
    private ShortDialog shortDialog;
    private long lastSyncTime;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_docket_summary;
    }

    @Override
    protected DocketLogPresenter createPresenter() {
        return new DocketLogPresenter();
    }

    @Override
    protected DocketQuery createQuery() {
        return new DocketQuery();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        tvTitle = fd(R.id.tv_title);
        tvRvTitle = fd(R.id.tv_rv_title);
        ivBack = fd(R.id.iv_back);
        llTruck = fd(R.id.ll_truck);
        llSearch = fd(R.id.ll_search);
        tvTruck = fd(R.id.tv_truck);
        tvToday = fd(R.id.tv_today);
        tvMonth = fd(R.id.tv_month);
        tvSite = fd(R.id.tv_site);
        tvDate = fd(R.id.tv_date);
        tvTruckSel = fd(R.id.tv_truck_sel);
        tvPlant = fd(R.id.tv_plant);
        tvSearch = fd(R.id.tv_search);
        tvStatus = fd(R.id.tv_status);
        adapter = new DocketLogAdapter(context, list, R.layout.rvitem_docket_summary);
        adapter.setOnItemClickListener((v, position) -> {
            try {
                LogUtil.getInstance().insertOrReplaceData("查看送貨單日誌" + list.get(position).getDocketNo());
                DocketUtil.getInstance().setLogDetail(true);
                DocketUtil.getInstance().setDocketId(list.get(position).getDocketId());
                EventBus.getDefault().post(new Event(EventCode.EVENT_LOG_DETAIL));
            } catch (Exception e) {
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
        MyOnClickListener onClickListener = new MyOnClickListener();
        tvSite.setOnClickListener(onClickListener);
        tvDate.setOnClickListener(onClickListener);
        tvTruckSel.setOnClickListener(onClickListener);
        tvPlant.setOnClickListener(onClickListener);
        ivBack.setOnClickListener(onClickListener);
        tvSearch.setOnClickListener(onClickListener);
        tvStatus.setOnClickListener(onClickListener);
        fd(R.id.btn_reset).setOnClickListener(onClickListener);
        fd(R.id.btn_search).setOnClickListener(onClickListener);
    }

    @Override
    protected void loadData() {
        mPresenter.getSummary(SPUtil.getInstance().getString(AllConstants.TRUCK_NAME));
        mPresenter.docketsLog(query, what);
    }

    @Override
    protected void initData() {
        showLoading();
        String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
        mPresenter.getSummary(truckNo);
        list.clear();
        query.init();
        String date = DateUtil.DateTimeToStr(new Date());
        query.setStartAt(date + " 00:00:00");
        query.setEndAt(date + " 23:59:59");
        query.setTruckNo(truckNo);
        what = "docketAt";
        mPresenter.docketsLog(query, what);
        tvTruck.setText(getString(R.string.truck1, truckNo));
        calendarStart = Calendar.getInstance();
        calendarEnd = Calendar.getInstance();
        tvTruckSel.setText(truckNo);
        tvTruckSel.setTag(truckNo);
    }

    @Override
    public void onGetDataSuccess(ApiResultData<PagedList<DocketDto>> apiResultData) {
        if (apiResultData.getStatus() == 2000) {
            list.addAll(apiResultData.getData().getList());
        } else {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
        }
        adapter.notifyDataSetChanged();
        if (isParam) {
            tvRvTitle.setText(getString(R.string.total, apiResultData.getData().getTotalCount()));
        }
        if (smartRefreshLayout.getTag() != null && smartRefreshLayout.getTag().equals(AllConstants.REFRESH)
                && System.currentTimeMillis() - lastSyncTime > 3000L) {
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOG_REFRESH_DOWNLOAD));
            lastSyncTime = System.currentTimeMillis();
        }
        refreshSmartRefreshLayout();
    }

    @Override
    public void onGetDataFail(Exception e) {
        refreshSmartRefreshLayout();
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_LOG_DOWNLOAD_SUCCESS && list.isEmpty()) {
            mPresenter.docketsLog(query, what);
        }
    }

    @Override
    public void onGetSummarySuccess(ApiResultData<DocketSummaryDto> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResultData.getMessage());
            return;
        }
        DocketSummaryDto data = apiResultData.getData();
        if (data == null) {
            return;
        }
        tvToday.setText(data.getTodayComQty() == null ? "0" : String.valueOf(data.getTodayComQty()));
        tvMonth.setText(data.getMonthComQty() == null ? "0" : String.valueOf(data.getMonthComQty()));
    }

    @Override
    public void onGetSummaryFail(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void onGetComListSuccess(ApiResultData<List<ShortDto>> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(context, apiResult.getMessage());
            return;
        }
        if (apiResult.getData() == null) {
            return;
        }
        shortDialog = new ShortDialog(context, tvSel == tvTruckSel, apiResult.getData(), R.string.p_sel,
                selId, bean -> {
            if (tvSel == tvTruckSel) {
                tvSel.setTag(bean.getName());
            } else {
                tvSel.setTag(bean.getId());
            }
            tvSel.setText(bean.getName());
        });
        shortDialog.setOnDismissListener(dialog -> shortDialog = null);
        shortDialog.show();
    }

    @Override
    public void onGetComListFails(Exception msg) {
        ToastDialogUtils.getInstance().showInfoMessage(context, R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.iv_back) {
                isParam = false;
                tvTitle.setText(R.string.docket_summary);
                tvRvTitle.setText(R.string.today_docket);
                tvSearch.setVisibility(View.VISIBLE);
                ivBack.setVisibility(View.GONE);
                llSearch.setVisibility(View.GONE);
                llTruck.setVisibility(View.VISIBLE);
                list.clear();
                query.init();
                query.initParam();
                String dateStr = DateUtil.DateTimeToStr(new Date());
                query.setStartAt(dateStr + " 00:00:00");
                query.setEndAt(dateStr + " 23:59:59");
                query.setTruckNo(SPUtil.getInstance().getString(AllConstants.TRUCK_NAME));
                mPresenter.docketsLog(query, what);
            } else if (id == R.id.tv_search) {
                isParam = true;
                tvTitle.setText(R.string.search);
                tvSearch.setVisibility(View.GONE);
                ivBack.setVisibility(View.VISIBLE);
                llSearch.setVisibility(View.VISIBLE);
                llTruck.setVisibility(View.GONE);
                reset();
                query.initParam();
                searchWithParam();
            } else if (id == R.id.tv_site) {
                selId = tvSite.getTag() != null ? tvSite.getTag().toString() : "";
                tvSel = tvSite;
                mPresenter.combo("sites");
            } else if (id == R.id.tv_date) {
                showDate();
            } else if (id == R.id.tv_truck_sel) {
                selId = tvTruckSel.getTag() != null ? tvTruckSel.getTag().toString() : "";
                tvSel = tvTruckSel;
                mPresenter.combo("trucks");
            } else if (id == R.id.tv_plant) {
                selId = tvPlant.getTag() != null ? tvPlant.getTag().toString() : "";
                tvSel = tvPlant;
                mPresenter.combo("plants");
            } else if (id == R.id.tv_status) {
                selId = tvStatus.getTag() != null ? tvStatus.getTag().toString() : "";
                tvSel = tvStatus;
                mPresenter.combo("driverJobStates");
            } else if (id == R.id.btn_reset) {
                reset();
                list.clear();
                query.init();
                query.initParam();
                query.setTruckNo(SPUtil.getInstance().getString(AllConstants.TRUCK_NAME));
                mPresenter.docketsLog(query, what);
            } else if (id == R.id.btn_search) {
                searchWithParam();
            }
        }
    }

    private void reset() {
        tvSite.setText("");
        tvSite.setTag(null);
        tvDate.setText("");
        Date date = new Date();
        calendarStart.setTime(date);
        calendarEnd.setTime(date);
//        tvTruckSel.setText("");
//        tvTruckSel.setTag(null);
        tvPlant.setText("");
        tvPlant.setTag(null);
        tvStatus.setText("");
        tvStatus.setTag(null);
    }

    private void searchWithParam() {
        showLoading();
        query.setSiteId(tvSite.getTag() == null ? null : tvSite.getTag().toString());
        query.setPlantId(tvPlant.getTag() == null ? null : tvPlant.getTag().toString());
        query.setDriverJobState(tvStatus.getTag() == null ? null : Integer.parseInt(tvStatus.getTag().toString()));
        query.setTruckNo(tvTruckSel.getTag() == null ? null : tvTruckSel.getTag().toString());
        if (!TextUtils.isEmpty(tvDate.getText().toString())) {
            query.setStartAt(DateUtil.DateTimeToStr(calendarStart.getTime()) + " 00:00:00");
            if (tvDate.getText().toString().length() > 10) {
                query.setEndAt(DateUtil.DateTimeToStr(calendarEnd.getTime()) + " 23:59:59");
            }
        } else {
            query.setStartAt(null);
            query.setEndAt(null);
        }
        list.clear();
        query.init();
        mPresenter.docketsLog(query, what);
    }

    private void showDate() {
        Calendar calendarSel;
        int title;
        if (isEnd) {
            calendarSel = calendarEnd;
            title = R.string.p_sel_end_date;
        } else {
            calendarSel = calendarStart;
            title = R.string.p_sel_start_date;
        }
        DateUtil.showDateSelector(context, title, tvDate, calendarSel, date -> {
            String time = DateUtil.DateTimeToStr(date);
            StringBuilder sb = new StringBuilder(tvDate.getText().toString());
            if (isEnd) {
                calendarEnd.setTime(date);
                isEnd = false;
                tvDate.setText(String.format("%s - %s", sb.substring(0, 10), time));
                return;
            }
            calendarStart.setTime(date);
            isEnd = true;
            if (TextUtils.isEmpty(sb.toString())) {
                tvDate.setText(time);
            } else {
                tvDate.setText(sb.replace(0, 10, time));
            }
            showDate();
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            list.clear();
            adapter.notifyDataSetChanged();
            if (isParam) {
                query.initParam();
                tvTitle.setText(R.string.docket_summary);
                tvRvTitle.setText(R.string.today_docket);
                tvSearch.setVisibility(View.VISIBLE);
                ivBack.setVisibility(View.GONE);
                llSearch.setVisibility(View.GONE);
                llTruck.setVisibility(View.VISIBLE);
            }
        } else {
            showLoading();
            String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
            mPresenter.getSummary(truckNo);
            query.init();
            query.setTruckNo(truckNo);
            tvTruck.setText(getString(R.string.truck1, truckNo));
            String dateStr = DateUtil.DateTimeToStr(new Date());
            query.setStartAt(dateStr + " 00:00:00");
            query.setEndAt(dateStr + " 23:59:59");
            calendarStart = Calendar.getInstance();
            calendarEnd = Calendar.getInstance();
            mPresenter.docketsLog(query, what);
            tvTruckSel.setText(truckNo);
            tvTruckSel.setTag(truckNo);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtil.getInstance().dialogDestroy(shortDialog);
    }
}

